﻿using System;
using System.Text;
using System.Net.Sockets;

namespace ClientAPI.Network
{
    class Messenger
    {
        private Socket _socket;
        private string _socketName;
        public bool _receiving;

        public Messenger(Socket socket, string name)
        {
            _socket = socket;
            _socketName = name;
            _receiving = true;
        }

        public void SendMessage(string message)
        {
            byte[] sendMess = Encoding.UTF8.GetBytes(message);

            System.Diagnostics.Debug.WriteLine("Message sent: " + message);

            _socket.Send(sendMess);
        }

        public void ReceiveMessage()
        {
            while (_receiving)
            {
                byte[] buffer = new byte[Settings.Instance.GetBufferSize()];
                _socket.Receive(buffer);
                CommandProtocol.Instance.MessageHandler(Encoding.UTF8.GetString(buffer));
                System.Diagnostics.Debug.WriteLine("Message Received: " + Encoding.UTF8.GetString(buffer));
                //return Encoding.UTF8.GetString(buffer);            
            }
        }

        public string ReceiveChatMessage()
        {
            byte[] buffer = new byte[Settings.Instance.GetBufferSize()];
            _socket.Receive(buffer);

            string message = Encoding.UTF8.GetString(buffer);

            return message;
        }

        public string ReceiveFileInformation()
        {
            byte[] buffer = new byte[Settings.Instance.GetFileBufferSize()];
            string message;
            try
            {
                int recivedbytes = _socket.Receive(buffer);
                if (recivedbytes == 0)
                {
                    message = null;
                }
                else
                {
                    message = Encoding.UTF8.GetString(buffer);
                    System.Diagnostics.Debug.WriteLine("Download Message Recived: " + message);
                }
            }
            catch (Exception err)
            {
                System.Diagnostics.Debug.WriteLine(err);
                message = null;
            }

            return message;
        }

        public void Disconnect()
        {
            _socket.Dispose();
            _socket.Disconnect(true);
        }
    }
}
